<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends MY_Controller {
    
    private $_emailConfig;
    
    public function __construct()
    {
        parent::__construct();  
        $this->load->model('users_mod');
        $this->load->model('moderators_mod');
        $this->load->library('email');
  
        // define terms for emails
		$this->_emailConfig['mailtype'] = 'html';
        $this->_emailConfig['useragent'] = 'PHP CodeIgniter';
    }
    
	/**
     *   
     *    
     */
    public function index( )
    {        
        $data['menu_page'] = "users"; // Koja je stranica. current menu item
        
        // Definisi koji se view ucitava
        $data['contents'] = 'users/home';
        
        $this->load->view('main',$data);
    }
    
    public function online()
    {
        $data['menu_page'] = "users"; // Koja je stranica. current menu item
        
        $data['online_users'] = $this->users_mod->getOnlineUsers();
        
        // Definisi koji se view ucitava
        $data['contents'] = 'users/online';
        
        $this->load->view('main',$data);
    }
    
    public function all_users()
    {
        $data['menu_page'] = "users"; // Koja je stranica. current menu item
        $filter = $this->input->post('filter');
        $data['filter'] = $filter;
        $data['all_users'] = $this->users_mod->getAllUsers($filter);
        $data['stats'] = count($data['all_users']);
        $data['states'] = $this->users_mod->getStates();
        $data['user_groups'] = $this->users_mod->getUserGroups();
        $data['teams'] = $this->moderators_mod->getTeams(true); // samo aktivne timove
        // Definisi koji se view ucitava
        $data['contents'] = 'users/all';

        $this->load->view('main',$data);
    }
    /*
    public function fake_users()
    {
        $data['menu_page'] = "users"; // Koja je stranica. current menu item
        $filter = $this->input->post('filter');
        $data['filter'] = $filter;
        $data['fake_users'] = $this->users_mod->getFakeUsers($filter);
        $data['stats'] = count($data['fake_users']);
        $data['states'] = $this->users_mod->getStates();
        $data['user_groups'] = $this->users_mod->getUserGroups();
        $data['teams'] = $this->moderators_mod->getTeams(true); // samo aktivne timove
        // Definisi koji se view ucitava
        $data['contents'] = 'users/fake';

        $this->load->view('main',$data);
    }
     * */
    public function moderation_users()
    {
        $data['menu_page'] = "users"; // Koja je stranica. current menu item
        $filter = $this->input->post('filter');
        $data['filter'] = $filter;
        $data['fake_users'] = $this->users_mod->getFakeUsers($filter);
        $data['stats'] = count($data['fake_users']);
        $data['states'] = $this->users_mod->getStates();
        $data['user_groups'] = $this->users_mod->getUserGroups();
        $data['teams'] = $this->moderators_mod->getTeams(true); // samo aktivne timove
        // Definisi koji se view ucitava
        $data['contents'] = 'users/fake';

        $this->load->view('main',$data);
    }
    
    /**
     *  AJAX
     *  Filer submit. Filtriranje usera 
     */
    public function filter_submit()
    {
        try{
          $filter = $this->input->post('filter');
          $data['all_users'] = $this->users_mod->getAllUsers($filter);
          $num_users = count($data['all_users']);
          $html = $this->load->view('users/all_users_list',$data,true);
          $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'num_users' => $num_users,
                        'html' => $html
                    );
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
      
    }
    
    /**
     *  AJAX
     *  Filer submit. Filtriranje usera 
     */
    public function fake_users_filter_submit()
    {
        try{
          $filter = $this->input->post('filter');
          $data['fake_users'] = $this->users_mod->getFakeUsers($filter);
          $num_users = count($data['fake_users']);
          $html = $this->load->view('users/fake_users_list',$data,true);
          $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'num_users' => $num_users,
                        'html' => $html
                    );
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
      
    }
    public function get_user_data()
    {
        try{       
          //$this->load->model('users_mod');
          $id = $this->input->post('id');
          
          if( $id == "" )
            throw new Exception(lang('user_not_selected'));
          
          $user = $this->users_mod->getUserData($id);
          $user['state_name'] = lang($user['state']);
          $user['gender_text'] = lang($user['gender']);
          $user['look_for_text'] = lang($user['look_for']);
          $data['user'] = $user;
          
          //$html = $this->load->view('users/user_form',$data,true);
          $html = "";
          $response = array(
                      'ind' => 1,
                      'msg' => "",
                      'html' => $html
                  );
          $response = array_merge($data['user'],$response);
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'html' => ''
            );
        }
        echo json_encode($response);
    }
    
    public function get_user_activity()
    {
        try{       
          //$this->load->model('users_mod');
          $id = $this->input->post('id');
          $result = $this->users_mod->getUserActivity($id);
          $data['user'] = $result['user'];
          $data['image'] = $result['image'];
          $data['messages'] = $result['messages'];
          $data['transactions'] = $result['transactions'];
          $html = $this->load->view('users/user_activity',$data,true);
          $response = array(
                      'ind' => 1,
                      'msg' => "",
                      'html' => $html
                  );
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'html' => ''
            );
        }
        echo json_encode($response);
    }
    public function save_user()
    {
        try{
          
          $user = $this->input->post('user');
          $fake_list = $this->input->post('is_fake_list');
          $this->users_mod->saveUser($user);
          if( $fake_list != 1 )
          {
            $data['all_users'] = $this->users_mod->getAllUsers();
            $data['stats'] = count($data['all_users']);
            $num_users = count($data['all_users']);
            $html = $this->load->view('users/all_users_list',$data,true);
          }
          else {
            $data['fake_users'] = $this->users_mod->getFakeUsers();
            $data['stats'] = count($data['fake_users']);
            $num_users = count($data['fake_users']);
            $html = $this->load->view('users/fake_users_list',$data,true);
          }
          $response = array(
                        'ind' => 1,
                        'msg' => "",
                        'num_users' => $num_users,
                        'html' => $html
                    );
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
    }
    
    
    public function add_to_spotlight()
    {
      try{
          
          $id = $this->input->post('id');
          
          if( true == $this->users_mod->addToSpotlight($id) )
          {
            $response = array(
                          'ind' => 1,
                          'msg' => lang('user_added_to_spotlight')                          
                      );
          }
          else
          {
            $response = array(
                          'ind' => 1,
                          'msg' => lang('user_not_added_to_spotlight')                          
                      );
          }
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage(),
                'num_users' => 0,
                'html' => ''
            );
        }
        echo json_encode($response);
    }
    
    public function send_user_mail()
    {
        try{
          
          $data = $this->input->post('mailto');
          //$message = $_POST['mailto[message]'];
          $message = $data['message'];
          $from = $this->config->item('admin_mail_from');
          if( $this->_send_mail($data['email'], $from, $data['subject'], $message) )
          {
            $response = array(
                        'ind' => 1,
                        'msg' => lang("mail_sent")
                    );
          }
          else
          {
              $response = array(
                        'ind' => 0,
                        'msg' => lang("mail_not_sent")
                    );
          }          
        }
        catch (Exception $e) {

            $response = array(
                'ind' => 0,
                'msg' => 'Following errors occured: <br />' . $e->getMessage()
            );
        }
        echo json_encode($response);
    }
    
    
   
    private function _send_mail( $to, $from, $subject, $message )
    {
        $this->email->clear();       
        $this->email->initialize($this->_emailConfig);
        
        $this->email->to( $to );
        $this->email->from($from);
        $this->email->subject( $subject );
        $this->email->message( $message );

        if (!$this->email->send())
        {
          // Generate error (by CI)
          throw new Exception("Email cannot be sent. Try again or contact admin!");
          return false;
        }
                
        //echo $this->email->print_debugger();
        return true;
    }
    
    
    public function insert_fake()
    {
      $this->load->library('csvreader');

      $filePath = $this->config->item('base_dir').'uploads/fake_users_3.csv';

      $csvData = $this->csvreader->parse_file($filePath);
      $this->load->helper('string');
      
      echo "<pre>";
      $i=1;
      $k='0';
      foreach ($csvData as $user)
      {        
        //$user['name'] = $user['username'];
        
        $user['coins'] = 100;
        $user['state'] = 'germany';
        $user['status'] = 1;
        $user['gender'] = 'female';
        $user['look_for'] = 'male';
        $user['is_fake'] = 1;
        $birthdate = 2013 - $user['year'];// - ($user['year']>20)?2:0;
        if( $user['year']>20 ) $birthdate = $birthdate + 2;
        $birthdate .= "-". ((int)random_string('numeric',2) % 12 + 1);
        $birthdate .= "-". ((int)random_string('numeric',2) % 28 + 1);
        $user['birthdate'] = $birthdate;
        unset($user['year']); 
        $user['zip_code'] = $k . random_string('numeric',4);
        $new_password = "user12345" ;//random_string('alnum', 8);
        $user['password'] = md5($new_password);
        $user['registration_date'] = date("Y-m-d H:i:s", time());
        
        $id = $this->users_mod->insertUser($user);
        if( $id != NULL )
        {
          $this->_createFolders ($id);          
          //$mess = sprintf($message, $user['username'],$user['username'],$new_password);
          //$this->_send_mail($user['email'], $from, $subject, $mess);
          //echo $mess;
        }
        
        print_r($user);
        //echo "User with Username: {$user['username']} is added...<br/>";
        $i++;
        if( $i>9 )
        {
          $k = $i % 10;
        }
      }
      echo "</pre>";
    }


    
    public function insert_users($file_nr = "")
    {
      ini_set('max_execution_time', 180000);
      $this->load->library('CSVReader');

      $filePath = $this->config->item('base_dir')."uploads/korisnici-{$file_nr}.csv";

      $csvData = $this->csvreader->parse_file($filePath);
      $from = "info@datyy.de";
 $subject = "Wir ziehen um!";
 $message="
   

<h3>Hallo %s,</h3>
<p>
wir freuen uns dir heute tolle Neuigkeiten mitteilen zu können:
</p>
<h4>
Wir ziehen um!
</h4>
<p>
wohin? Zu datyy.de! Du wirst dich sicher fragen warum und die Antwort ist relativ simpel: weil wir DIR einfach MEHR bieten wollen! Bei datyy.de wird es in Zukunft viele tolle neue Funktionen geben und vor allem ein übersichtlicheres Design! Damit der Umzug für dich so entspannt wie möglich verläuft schenken wir dir noch einen Gutschein-Code über 50 Gratis-Coins! Diesen werden wir dir mit einer gesonderten Mail zuschicken!
</p>
<p>
Deine Zugangsdaten haben wir direkt übernommen:
</p>
<p>
Username: %s <br/>
Passwort: %s
</p>
<p>
Wir empfehlen dir aus Sicherheitsgründen das Passwort nach dem ersten Login zu ändern.
</p>
<p>
Bis bald im \"neuen Zuhause\"!
<p>
<p>
Dein Team von Datyy.de (ehemals Flirtyy.de)
</p>
";
      
      
      echo "<pre>";
      foreach ($csvData as $user)
      {        
        $user['coins'] = 100;
        $user['state'] = 'germany';
        $user['status'] = 1;
        $user['birthdate'] = substr($user['birthdate (year)'], 0, 10);
        unset($user['birthdate (year)']); 
        $this->load->helper('string');
        //$new_password = random_string('alnum', 8);
        //$user['password'] = md5($new_password);
        $user['registration_date'] = date("Y-m-d H:i:s", time());
        
        $id = $this->users_mod->insertUser($user);
        if( $id != NULL )
        {
          $this->_createFolders ($id);          
          //$mess = sprintf($message, $user['username'],$user['username'],$new_password);
          //$this->_send_mail($user['email'], $from, $subject, $mess);
          //echo $mess;
        }
        
        print_r($user);
        //echo "User with Username: {$user['username']} is added...<br/>";
      }
      echo "</pre>";
      //$data['csvData'] = $csvData;
      //$this->load->view('insert_users', $data);
    }
    
    private function _createFolders($id)
    {
        $base_dir = $this->config->item('image_path');
        @mkdir($base_dir.$id);
        
        $big = $base_dir.$id."/big"; // Za velike slike (max 1024x...)
        @mkdir($big);
        
        $small = $base_dir.$id."/small"; // Za male slicice (230x...)
        @mkdir($small); 
        
        $thumb = $base_dir.$id."/thumb"; // Za male slicice (100x100)
        @mkdir($thumb); 
        
        // Kopiranje index.html file-a
        $source = $base_dir."index.html";
        $dest = $base_dir.$id."/index.html";
        $dest1 = $big."/index.html";
        $dest2 = $small."/index.html";
        $dest3 = $thumb."/index.html";
        @copy($source, $dest);
        @copy($source, $dest1);
        @copy($source, $dest2);
        @copy($source, $dest3);
    }
}
/* End of file users.php */
/* Location: ./application/controllers/users.php */